using System;
using System.Data;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
//using ctsu.Data;
using Syncfusion.Windows.Forms.Grid;
using ctsu.BaseForms;
using ctsu.CustomControls;
using ctsu.Shared;

namespace ctsu.Admin.BusLogic
{
	public class BLFormGridProtocolImpl : BLFormGridBaseImpl
	{
		public BLFormGridProtocolImpl(FormGridMeta formGridMeta, UserGrid uGrid, FormInfoBase formInfo, Form form)
			: base(formGridMeta, uGrid, formInfo, form)
		{

		}

		public override bool VerifyGrid(out string message, out ProtocolGridValidationErrorType errType)
		{
			errType = ProtocolGridValidationErrorType.none;
			message = "";
			StringBuilder sb = new StringBuilder();

			GridControl grid = this._uGrid.Grid;
			DataRow dr = null;
			int rows = grid.RowCount;

			if (this._formGridMeta.IsRequired)
			{
				if (rows == 0)
				{
					errType = ProtocolGridValidationErrorType.rowRequired;
					sb.Append("At least one grid row is required!");
					message = sb.ToString();
					return false;
				}
			}

			//iterate thru each row
			for (int i = 1; i < rows + 1; i++)
			{
				//check the dataRowState of the dr
				dr = (DataRow)grid[i, 0].Tag;
				if (dr.RowState == DataRowState.Unchanged)
					continue;

				if (!VerifyRow(i, 2, out message))
				{
					errType = ProtocolGridValidationErrorType.fieldRequired;
					return false;
				}
			}
			return true;
		}

		protected override bool VerifyRow(int row, int validationType, out string message)
		{
			message = "";
			GridControl grid = this._uGrid.Grid;
			StringBuilder sb = new StringBuilder();
			string errMessage = "";
			//iterate thru each column and call a verify method
			for (int i = 1; i < grid.ColCount + 1; i++)
			{
				DataColumn dc = (DataColumn)this._uGrid.Grid[0, i].Tag;
				if (!this._formGridMeta.GridColumns.Contains(dc.ColumnName))
					continue;

				FormGridColumnMeta fgcm = (FormGridColumnMeta)this._formGridMeta.GridColumns[dc.ColumnName];

				if (validationType == 2)
				{
					if (fgcm.ValidationType < 2)
						continue;
				}

				BindingFlags bf = BindingFlags.NonPublic | BindingFlags.Instance;
				string text = grid[row, i].CellValue.ToString();

				if (fgcm.VerifyName.Length == 0)
					continue;
				MethodInfo mi = this.GetType().GetMethod(fgcm.VerifyName, bf);
				if (mi == null)
					continue;

				object[] o = { fgcm, text, row.ToString() };
				bool b = (bool)mi.Invoke(this, o);

				if (!b)
				{
					errMessage = GetErrorMessage();
					sb.Append("Grid Error:");
					sb.Append(Environment.NewLine);
					sb.Append(errMessage);
					message = sb.ToString();
					return false;
				}
			}
			return true;
		}

	}
}
